// controllers/wordController.js
const Word = require("../models/word");

const wordController = {
	createWord: (req, res) => {
		const { name, description, samewordlist } = req.body;
		if (!name || !description || !samewordlist) {
			return res.status(200).send({
				message: "单词名/描述/同义词不能为空",
				success: false,
			});
		}

		Word.create({ name, description, samewordlist }, (error, results) => {
			if (error) {
				res.status(200).send({
					message: error.message,
					success: false,
				});
			} else {
				res.status(200).send({
					message: "创建成功",
					id: results.insertId,
					success: true,
				});
			}
		});
	},
	updateWord: (req, res) => {
		const { id, name, description, samewordlist } = req.body;
		if (!id) {
			res.status(200).send({ message: "id为空", success: false });
		}
		Word.update(
			id,
			{ name, description, samewordlist },
			(error, results) => {
				if (error) {
					res.status(200).send({
						message: error.message,
						success: false,
					});
				} else if (results.affectedRows === 0) {
					res.status(200).send({ message: "error", success: false });
				} else {
					res.status(200).send({
						message: "更新成功",
						success: true,
					});
				}
			}
		);
	},
	deleteWord: (req, res) => {
		const { id } = req.body;
		if (!id) {
			res.status(200).send({ message: "id为空", success: false });
		}
		Word.delete(id, (error, results) => {
			if (error) {
				res.status(200).send({
					message: error.message,
					success: false,
				});
			} else if (results.affectedRows === 0) {
				res.status(200).send({ message: "单词不存在", success: false });
			} else {
				res.status(200).send({ message: "删除成功", success: true });
			}
		});
	},
	findWordByName: (req, res) => {
		const { name } = req.body;
		if (!name) {
			return res
				.status(200)
				.send({ message: "不能为空", success: false });
		}

		Word.findOneByName(name, (error, results) => {
			if (error) {
				res.status(200).send({
					message: error.message,
					success: false,
				});
			} else if (results.length === 0) {
				res.status(200).send({
					message: "单词不存在",
					success: false,
				});
			} else {
				const list = results.filter(ele => {
					return name === ele.name;
				});
				res.status(200).send({
					data: [
						...list,
						...results.filter(ele => {
							return name !== ele.name;
						}),
					],
					success: true,
				});
			}
		});
	},
	getWordAll: (req, res) => {
		// 从请求中获取page和limit参数
		const page = parseInt(req.query.page, 10) || 1; // 默认为第1页
		const limit = parseInt(req.query.limit, 10) || 10; // 默认每页显示10条记录
		Word.findAll(page, limit, (error, results) => {
			if (error) {
				res.status(200).send({
					message: error.message,
					success: false,
				});
			} else {
				// 返回分页数据
				res.status(200).send({
					data: results,
					page: page,
					limit: limit,
					success: true,
				});
			}
		});
	},
	// 可能的其他控制器方法...
};

module.exports = wordController;
